#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion

using System.Collections.Generic;
using UnityEngine;

namespace Neatly.UI
{
    internal sealed class UIBehaviourPool<T> where T : MonoBehaviour
    {
        List<T> pool = new List<T>();

        public int Count { get { return pool.Count; } }

        public T Create(Transform parent)
        {
            T t;

            if (Count > 0)
            {
                t = pool[pool.Count - 1];
                pool.RemoveAt(pool.Count - 1);
                t.gameObject.SetActive(true);
            }
            else
            {
                GameObject go = new GameObject();
                go.hideFlags = HideFlags.HideInHierarchy;
                go.transform.SetParent(parent);
                t = go.AddComponent<T>();
            }
            return t;
        }

        public void Release(T t)
        {
            t.gameObject.SetActive(false);
            pool.Add(t);
        }

        public void Release(List<T> list)
        {
            if (list == null) return;
            for (int i = list.Count - 1; i >= 0; i--)
            {
                Release(list[i]);
                list.RemoveAt(i);
            }
        }

        public void Release(List<T> list, int count)
        {
            if (list == null) return;
            int sum = 0;
            for (int i = list.Count-1; i >=0; i--)
            {
                sum++;
                Release(list[i]);
                list.RemoveAt(i);
                if (sum>=count)
                {
                    return;
                }
            }
        }
    }
}
